import datetime
import re
from flask import Flask,Blueprint,request,jsonify
from database import *
from conf.comm import sqlalchemy_context
import json


#实例化蓝图
bp_lianxi = Blueprint('lianxi',__name__)



#删改查  cate
@bp_lianxi.route('/lianxi/',methods=['POST','GET','PUT','DELETE'])
@sqlalchemy_context()
def lianxi():
    if request.method=='POST':
        data = request.data
        if data:
            data = json.loads(request.data)
        else:
            data=request.form
        cate = Cate(name=data['name'])
        db.session.add(cate)
        db.session.commit()
        return jsonify({"code":200})


    elif request.method=='GET':

        page = int(request.args.get('page'))
        page_size = 3
        start = (page-1)*page_size
    
        cate = Cate.query.all()
        
        if page:
            cates = Cate.query.offset(start).limit(page_size)
            list = []
            for i in cates:
                dic={}
                dic['id']=i.id
                dic['name']=i.name
                list.append(dic)
            return jsonify({"code":200,'list':list})
        else:
            list = []
            for i in cate:
                dic={}
                dic['id']=i.id
                dic['name']=i.name
                list.append(dic)
            return jsonify({"code":200,'list':list})




    elif request.method=='PUT':
        id = request.args.get('id')
        name = request.args.get('name')
        if not id:
            return jsonify({"code":10011})
        #根据id删除
        Cate.query.filter_by(id=id).update({'name':name})
        db.session.commit()
        #返回结果
        return jsonify({'code':200})


    else :
        id = request.args.get('id')
        if not id:
            return jsonify({"code":10010})
        #根据id删除
        Cate.query.filter_by(id=id).delete()
        db.session.commit()
        #返回结果
        return jsonify({'code':200})